<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>防抖与节流</title>
    </title>
</head>

<body>
    <input type="button" value="防抖" onclick="onclick1()">
    <input type="button" value="节流" onclick="onclick2">
    <button id="throttle">点我节流！</button>
</body>

</html>

<script>
  // 1.防抖 debounce
  // n秒内只执行一次，若在n秒内重复触发，生效一次

  function debounce(fn, delay) {
    let timer = null
    return function() {
        clearTimeout(timer)
        timer = setTimeout(() => {
            // fn.apply(this, arguments)
            fn()
        }, delay)
    }
  }

  let fn1 = debounce(() => {
        console.log('防抖执行了')
  }, 1000)

  function onclick1() {
    fn1()
  }


  // 2.节流
  // 相当于是一个定期开发的阀门，事件触发时就让函数执行一次，然后关闭阀门，过了一段时间之后这个阀门再打开
  function throttle1(fn, delay) {
    let timer = null
    return function (...args) {
        if (!timer) {
            timer = setTimeout(() => {
                // fn.apply(this, args)
                fn()
            }, delay);
        }
    }
  }

  let fn2 = throttle1(() => {
    console.log('节流执行了')
  }, 1000)

  function onclick2() {
    fn2()
  }

  // 节流
  function throttle(fn, wait = 1000) {
        let timer = null
        return function (...args) {
            if (!timer) {
                timer = setTimeout(() => {
                    // fn.apply(this, args);
                    fn()
                    timer = null;
                }, wait);
            }
        }
    }
    function sayThrottle() {
      console.log("节流成功！");
    }
    window.onload = function () {
        var myThrottle = document.getElementById("throttle");
        myThrottle.addEventListener("click", throttle(sayThrottle));
    }
</script>